import { useEffect, useState } from "react";
import { Modal,  Select, message, FormInstance ,Row, Button, Popconfirm} from "antd";
import { getPower, addUser, getUser, editUser } from "@/api";

import {getFeedBacklog, delMenu } from "@/api";

import MenuModal from "@/components/modal/menu";
import MyTable from "@/components/table";
import MyIcon from "@/components/icon";
import { FeedbackEntityList, MapKey,GetFeedBackLogBaseRestResponse,FeedbackItem } from "@/types"
import "./index.less";
export type ModalType = "add" | "addChild" | "edit"
import { Tooltip } from 'antd';
import { json } from "stream/consumers";
import axios, { AxiosResponse, AxiosError } from "axios";
interface VehicleProps {
  vin: string | null
  isShow: boolean | null
  onCancel: (id: string | null, s: boolean) => void
  onOk: () => void
}

export type SelectInfo = {
  [MENU_KEY]?: string
  isParent?: Boolean
}


function useMenu() {
  const [menus, setMenu] = useState<FeedbackEntityList>([]);
  const [tabCol, setCol] = useState<MapKey>([]);
  const [selectInfo, setSelectInfo] = useState<SelectInfo>({});
  const [showModal, setShowModal] = useState(false);
  const [modalType, setModalType] = useState<ModalType>('add');


  // const menuAction = {
  //   title: "操作",
  //   dataIndex: "action",
  //   key: "action",
  //   align: "center",
  //   hidden:false,
  //   render: (text: any, record: any) => {
  //     return (
  //       <Row>
  //         <Button type="link" onClick={() => openModal("edit", record)}>
  //           编辑
  //         </Button>
  //         <Button type="link" onClick={() => openModal("addChild", record)}>
  //           添加子菜单
  //         </Button>
  //       </Row>
  //     );
  //   },
  // };

  const menux = {
    title: '内容',
    dataIndex: 'content',
    key: "menux",
    align: "center",
    hidden:false,
    render: (text : any) => (
      <div style={{ maxWidth: 150, overflow: 'hidden', textOverflow: 'ellipsis' }}>
        {text.slice(0, 20) + (text.length > 20 ? '...' : '')}
      </div>
    )
  }
  
  const downloadLog = async (url: string) => {
    console.info("url::"+JSON.stringify(url));
    try{
    const response = await axios.get(url, {
      responseType: 'blob', // 处理二进制数据 [[9]]
    });
    const blob = new Blob([response.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', 'logfile'); // 设置文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl); // 释放内存
  } catch (error) {
    console.error('下载失败:', error);
  }
  };


  const getMenuList = (data:FeedbackItem) => {
        getFeedBacklog(data).then((res) => {

          if (res) {
            const {data, statusCode, statusMessage } = res;
            if(res.data){
              //data.mapKey.push(menux);
              data.mapKey.forEach((item) => {
                if (item.dataIndex === "icon") {
                  item.render = (text: string | null) =>
                    text ? <MyIcon className="preview" type={text} /> : "暂未设置";
                } else if (item.dataIndex === MENU_KEEPALIVE) {
                  item.render = (text: string) => (text === "true" ? "保持" : "关闭销毁");
                } else if (item.dataIndex === MENU_SHOW) {
                  item.render = (t: string) => t === "true" ? '显示' : '隐藏'
                } else if (item.dataIndex === "content" ){
                  item.render =   (text : any) => (
                    <Tooltip title={text}>
                    <div style={{ 
                      maxWidth: 300, 
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap' 
                    }}>
                      {text}
                    </div>
                  </Tooltip>
                  )
                } else if (item.dataIndex === "appLogUri" ){
                  console.info("item::"+JSON.stringify(item));
                  item.render = (text: string) => 
                    text != null && text !== "" && text ? (
                      <div>
                        <button onClick={() => downloadLog(text)}>下载</button>
                      </div>
                    ) : "未上传";
                } else if (item.dataIndex === "tboxLogUri" ){
                  item.render = (text: string) => 
                    text != null && text !== "" && text  ? (
                      <div>
                        <button onClick={() => downloadLog(text)}>下载</button>
                      </div>
                    ) : "未上传";
                } else if (item.dataIndex === "images" ){
                  item.render = (text: string) => 
                    text != null && text !== "" && text  ? (
                      <div>
                        <button onClick={() => downloadLog(text)}>下载</button>
                      </div>
                    ) : "未上传";
                } 
              });
              setCol(data.mapKey);
              setMenu(data.list);
            }

          }
        });
  };

  // useEffect(() => {
  //   getMenuList();
  //   // eslint-disable-next-line
  // }, []);

  const openModal = (type: ModalType, { [MENU_KEY]: key, isParent }: SelectInfo) => {
    setSelectInfo({ [MENU_KEY]: key, isParent: !Boolean(isParent) });
    setModalType(type);
    setShowModal(true);
  };


  const addMenu = () => {
    openModal("add", {});
  };
  return {
    selectInfo,
    menus,
    showModal,
    modalType,
    tabCol,
    setShowModal,
    getMenuList,
    addMenu,
  };
}



export default function VehicleModal({ vin, isShow, onCancel, onOk }: VehicleProps) {
  useEffect(() => {
    if (isShow) {
      console.info("VehicleModal::VIN::"+JSON.stringify(vin));
      if(vin){
        let data = {
          "vin":vin,
          "page":"1",
          "size":"10"
        } ;
        getMenuList(data);
      }

    }
  }, [isShow]);

  const submit = () => {
  };

  const close = () => {
    onCancel(null, false);
  };

  const {selectInfo, menus, showModal, modalType, tabCol, setShowModal, getMenuList, addMenu} = useMenu();

  return (
    <Modal
      maskClosable={false}  
      title={vin ? "日志管理A" : "日志管理B"}
      open={isShow}
      okText="确认"
      cancelText="取消"
      onCancel={close}
      onOk={submit} 
      width="100%"
      //bodyStyle={{ height: "60vh", overflow: "auto" }}
    >

    <MyTable  
    dataSource={menus} 
    rowKey={'key'} 
    columns={tabCol} 
    saveKey="MENUTABLE" />

    </Modal>
  );
}
